import { obj_int, uDb, reload_col, add_ck_col, ck_empty, ck_int, ck_date, loc, obj_str, d_sort, cline } from 'sui';

const load_sale = (hDone, setMain) => {
    uDb(hDone, "sale/list", { line: cline() },
        r => {
            d_sort(r, "sn");

            r.forEach((d, i) => {
                d["index"] = i + 1;
                d["dnum"] = obj_int(d, "pnum") - obj_int(d, "num");
            });

            setMain(r);
        },
        e => {
            setMain(null);
        });
};

const get_ck = (cur, main, col) => {
    const ret = {
        sn : v => null,
        tech: v => ck_empty(v),
        pnum: v => ck_int(v),
        pend: v => ck_date(v),
    };

    add_ck_col(ret, col);

    return ret;
};

const fix_col = () => {
    return [
        {sn: "sn", name: loc("l_518"), tp: "string"},
        {sn: "custom", name: loc("l_520"), tp: "string", ctp: "list"},
        {sn: "tech", name: loc("l_132"), tp: "string", ctp: "list"},
        {sn: "pend", name: loc("l_521"), tp: "string", ctp: "datetime"},
        {sn: "pnum", name: loc("l_455"), tp: "num"},
    ];
};

const load_col = (setCol) => {
    const fix = fix_col();
    reload_col(null, v => setCol(v), "sangle", fix);
};

const load_custom = (setMain) => {
    uDb(null, "file/list/custom", { line: cline() },
        r => {
            d_sort(r, "sn");

            r.forEach(d => d["name"] = d.sn);

            setMain(r);
        },
        e => setMain(null));
};

const update_sale = (umd, v, h, setMain) => {
    umd.startWait();

    uDb(null, "code/gen",
        {
            line: cline(),
            rule: "sale",
        },
        r => {
            const sn = obj_str(r, "psn");
            v["sn"] = sn;

            uDb(null, "sale/add", { line: cline(), v: v },
                r => {
                    load_sale(umd.endWait, setMain);
                    if (h) {
                        h();
                    }
                },
                e => umd.setErr(loc("l_755")));
        },
        e => umd.setErr(loc("l_755")));
};

const md_sale = (umd, v, setMain) => {
    umd.startWait();

    uDb(null, "sale/mditem", { line: cline(), v: v },
        r => load_sale(umd.endWait, setMain),
        e => umd.setErr(loc("l_755")));
};

export {md_sale, update_sale, load_custom, load_col, get_ck, load_sale};
